<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="Port 口名称" prop="portName">
        <el-input
          v-model.trim="queryParams.portName"
          placeholder="请输入Port 口名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadTemplate"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入 Port 口信息" 
          url="/api/port/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
          />
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" :height="tableHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="Port 口名称" align="center" prop="portName" />
      <el-table-column label="Port 口 ID" align="center" prop="portId" />
      <el-table-column label="状态" align="center" prop="status">
          <!-- <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1 || 2"
            :loading="switchLoading[scope.row.portId]"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            @change="changeStatus(scope.row)"
          /> -->
        <template #default="scope">
          <dict-tag :options="port_status" :value="scope.row.status"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="Port 口类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="port_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="Port 口储位" align="center" prop="storagePortId" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" fixed="right">
        <template #default="scope">
          <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:info:edit']">修改</el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[10, 30, 50, 100]"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改Port口信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="Port 口名称" prop="portName">
          <el-input v-model="form.portName" placeholder="请输入 Port 口名称" />
        </el-form-item>
        <el-form-item label="Port 口状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择"> 
            <el-option
              v-for="item in port_status"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Port 口类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in port_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Port 口储位" prop="storagePortId">
          <el-input v-model="form.storagePortId" placeholder="Port 口储位" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="portManagement">
import { listInfo, getInfo, delInfo, addInfo, updateInfo, updatePortAPI } from "@/api/work/portManagement"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'

const { proxy } = getCurrentInstance()
const { port_status, port_type } = proxy.useDict('port_status', 'port_type')

const infoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 添加switch的loading状态存储对象
const switchLoading = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    portName: null,
    portType: null,
    businessType: null,
    status: null,
    location: null,
  },
  rules: {
    portName: [
      { required: true, message: '请输入 Port 口名称', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请输入 Port 口状态', trigger: 'change' }
    ],
    // Port口类型 - 必填
    type: [
      { required: true, message: '请输入 Port 口类型', trigger: 'change' }
    ],
    // Port口储位 - 必填
    storagePortId: [
      { required: true, message: '请输入 Port 口储位', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询Port口信息列表 */
function getList() {
  loading.value = true
  listInfo(queryParams.value).then(res => {
    if (res.errCode === '1') {
      infoList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    portId: null,
    portName: null,
    portType: null,
    businessType: null,
    status: null,
    location: null,
    remark: null,
    storagePortId: null,
    createdBy: null,
    createTime: null,
    updatedBy: null,
    updateTime: null
  }
  proxy.resetForm("infoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.portId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加 Port 口信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _portId = row.portId || ids.value
  getInfo(_portId).then(res => {
    form.value = res.data.portInfo
    open.value = true
    title.value = "修改 Port 口信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.portId != null) {
        updateInfo(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addInfo(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

// 切换状态 - 添加loading处理
const changeStatus = async(row) => {
  console.log(row.status)
  // 设置当前行的switch为loading状态
  switchLoading.value[row.portId] = true
  try {
    const submitForm = {
      portId: row.portId,
      status: row.status
    }
    const res = await updatePortAPI(submitForm)
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess('更新成功')
    } else {
      getList()
      proxy.$modal.msgError(res.msg)
    }
  } catch(err) {
    getList()
  } finally {
    // 无论成功失败，都关闭loading
    switchLoading.value[row.portId] = false
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _portIds = row.portId || ids.value
  proxy.$modal.confirm('是否确认删除 Port 口信息编号为"' + _portIds + '"的数据项？').then(function() {
    return delInfo(_portIds)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('api/port/export', {
    ...queryParams.value
  }, `port口管理数据_${new Date().getTime()}.xlsx`)
}

getList()

// 下载模板
const downloadTemplate = async() => {
  proxy.download('/api/port/downloadTemplate', {}, `port 口管理模板_${new Date().getTime()}.xlsx`)
}
// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}
// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
}
</script>
